﻿using System;
using System.Diagnostics;

namespace MC2Development.DevWebServer
{
    /// <summary>
    /// Tracer class used to write trace output to configured listeners
    /// </summary>
    internal class Tracer : IDisposable
    {
        private string m_strCaller = String.Empty;

        /// <summary>
        /// Default constructor used to create a new tracer instance and
        /// write trace output indicating the calling method has started
        /// </summary>
        public Tracer()
        {
            m_strCaller = new StackFrame(1).GetMethod().Name;
            WriteTraceEntryImpl(String.Format("{0} started.", m_strCaller));
        }

        /// <summary>
        /// Writes trace output indicating the calling method has completed
        /// and disposes of the tracer instance.
        /// </summary>
        public void Dispose()
        {
            WriteTraceEntryImpl(String.Format("{0} ended.", m_strCaller));
        }

        /// <summary>
        /// Writes text to the trace output
        /// </summary>
        /// <param name="text">The text to write to the trace</param>
        public static void WriteTraceEntry(string text)
        {
            WriteTraceEntryImpl(text);
        }

        /// <summary>
        /// Writes text to the trace output
        /// </summary>
        /// <param name="formattedText">The text to write to the trace with formatting placeholders</param>
        /// <param name="args">Arguments to insert into the formatted text</param>
        public static void WriteTraceEntry(string formattedText, params string[] args)
        {
            WriteTraceEntryImpl(string.Format(formattedText, args));
        }

        /// <summary>
        /// Writes text to the trace output
        /// </summary>
        /// <param name="text">The text to write to the trace</param>
        private static void WriteTraceEntryImpl(string text)
        {
            Trace.WriteLine(String.Format("{0} - {1}", 
                                DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"), text));
        }
    }
}
